package com.ws.gold.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ws.gold.domain.WarehouseHoldSituation;
import com.ws.gold.mapper.WarehouseHoldSituationMapper;
import com.ws.gold.service.WarehouseHoldSituationService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * @author ws
 * @create 2025/6/27
 */
@Service
public class WarehouseHoldSituationServiceImpl extends ServiceImpl<WarehouseHoldSituationMapper, WarehouseHoldSituation> implements WarehouseHoldSituationService {
    @Override
    public WarehouseHoldSituation addNew(WarehouseHoldSituation warehouseHoldSituation) {

        //获取库中现在信息
        WarehouseHoldSituation holdSituation = lambdaQuery().list().stream().findFirst().orElse(null);
        //整理当前数据
        if (ObjUtil.isNotEmpty(holdSituation)) {
            removeById(holdSituation.getId());
            //第一次买入的实时价格
            BigDecimal multiply = BigDecimal.valueOf(holdSituation.getBuyRealPrice()).multiply(BigDecimal.valueOf(holdSituation.getHoldNum()));
            //第二次买入的实时价格
            BigDecimal multiply1 = BigDecimal.valueOf(warehouseHoldSituation.getBuyRealPrice()).multiply(BigDecimal.valueOf(warehouseHoldSituation.getHoldNum()));
            warehouseHoldSituation.setBuyRealPrice(multiply.add(multiply1).divide(BigDecimal.valueOf(holdSituation.getHoldNum()).add(BigDecimal.valueOf(warehouseHoldSituation.getHoldNum())), 4, RoundingMode.HALF_UP).doubleValue());
            warehouseHoldSituation.setHoldNum(warehouseHoldSituation.getHoldNum()+holdSituation.getHoldNum());
            warehouseHoldSituation.setHoldCostPrice(warehouseHoldSituation.getHoldCostPrice()+holdSituation.getHoldCostPrice());
            warehouseHoldSituation.setHoldCostPriceAvg(BigDecimal.valueOf(warehouseHoldSituation.getHoldCostPrice()).divide(BigDecimal.valueOf(warehouseHoldSituation.getHoldNum()), 4, RoundingMode.HALF_UP).doubleValue());
        }else {
            warehouseHoldSituation.setHoldCostPriceAvg(BigDecimal.valueOf(warehouseHoldSituation.getHoldCostPrice()).divide(BigDecimal.valueOf(warehouseHoldSituation.getHoldNum()), 4, RoundingMode.HALF_UP).doubleValue());
        }
        save(warehouseHoldSituation);
        return warehouseHoldSituation;
    }
}
